package cn.fancy.sdk.floatwindow;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.fancy.sdk.utils.CommMessage;

public class FloatWindowService extends Service {

	private Handler handler = new Handler();
	public Timer timer;

	public static boolean canopenfloat = true;
	public static boolean isshowflat = false; // 判断是否显示着浮窗内容
	public static Context AppContent = null;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (timer == null) {
			timer = new Timer();
			timer.scheduleAtFixedRate(new RefreshTask(), 0, 1000);
		}
		Log.e("floatservicestart", "floatservicestart");
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (timer != null) {
			timer.cancel();
		}
		timer = null;
		MyWindowManager.removefloatWindow(AppContent);
	}
	
	class RefreshTask extends TimerTask {
		@Override
		public void run() {
			if (!isHome() && !MyWindowManager.isWindowShowing()) { // 当前没有悬浮窗显示，则创建悬浮窗
				if (!canopenfloat) {
					return;
				}
				if (isshowflat) {
					return;
				}
				if (!CommMessage.isHavedlogin()) {
					return;
				}
				handler.post(new Runnable() {
					@Override
					public void run() {
						MyWindowManager.createfloatWindow(AppContent);
						Log.e("float service", "float1" + isshowflat);
					}
				});
			} else if (isHome() && MyWindowManager.isWindowShowing()) { // 当前是桌面且有悬浮窗，则去除悬浮窗
				handler.post(new Runnable() {
					@Override
					public void run() {
						FloatBallView.moveaction = 3;
						MyWindowManager.removefloatWindow(AppContent);
					}
				});
			}
		}
	}

	private boolean isHome() {
		ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);

		if (AppContent == null) {
			return true;
		}

		if (!rti.isEmpty()) {
			ComponentName topActivity = rti.get(0).topActivity;

			String localAppPackage = AppContent.getPackageName();
			String activityPackage = topActivity.getPackageName();
			boolean isActivity = activityPackage.equals(localAppPackage);
			return !isActivity;
		}

		return true;
	}
}
